package cn.edu.zafu.bigdata.x.sxy;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

public class UDPServer {
    DatagramSocket socket = null;

    public void serverWork() throws IOException{
        int prot = 3000;
        socket = new DatagramSocket(prot);
        System.out.println("UDP server is running...");

        while (true){
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            long serverTime = System.currentTimeMillis();

            InetAddress clientAddress = receivePacket.getAddress();
            int clientProt = receivePacket.getPort();
            ByteBuffer.wrap(sendData).putLong(serverTime);
            DatagramPacket sendpacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientProt);
            socket.send(sendpacket);
        }
    }

    public static void main(String[] args) {
        UDPServer server = new UDPServer();
        try {
            server.serverWork();
        }catch (IOException e){}
    }
}
